package com.io.commonlib.helper

import android.app.ActivityManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build

class AppInfoHelper {
    private val TAG = AppInfoHelper::class.java.simpleName

    /**
     * 获取应用版本号-versionName
     */
    fun getAppVersionName(ctx: Context): String {
        //0代表获取版本信息
        var packageInfo = ctx.packageManager.getPackageInfo(ctx.packageName, 0)
        packageInfo ?. let {
            return it.versionName
        } ?: let {
            return ""
        }
    }

    /**
     * 获取应用版本号-versionCode
     */
    fun getAppVersionCode(ctx: Context): Long {
        //0代表获取版本信息
        var packageInfo = ctx.packageManager.getPackageInfo(ctx.packageName, 0)
        packageInfo ?. let {
            return if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
                it.longVersionCode
            } else{
                it.versionCode.toLong()
            }
        } ?: let {
            return 0
        }
    }


    /**
     * 判断应用是否正在运行
     */
    fun isAppRunning(ctx: Context, packageName: String):Boolean{
        val am = ctx.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val infos = am.runningAppProcesses
        for(rapi in infos){
            if(rapi.processName == packageName){
                return true
            }
        }
        return false
    }

    /**
     * 获取该应用的私有文件夹地址
     */
    fun getLocalFilePath(ctx: Context): String{
        return ctx.filesDir.absolutePath
    }

    /**
     * 启动指定的应用
     */
    fun startApp(ctx: Context, packageName: String){
        LogHelper.d(TAG, "开始启动app了")
        val myPackageManager = ctx.packageManager
        val intent = myPackageManager
            .getLaunchIntentForPackage(packageName)
        ctx.startActivity(intent)
    }

    /**
     * 将指定应用置顶
     */
    fun setTopApp(context: Context, packageName: String){
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val taskInfos = activityManager.getRunningTasks(100)
        for(taskInfo in taskInfos){
            if(taskInfo.topActivity?.packageName == packageName){
                activityManager.moveTaskToFront(taskInfo.id, 0)
                break
            }
        }
    }
}